import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import axios from 'axios';
import qs from 'qs';

// 创建axios实例
const http: AxiosInstance = axios.create({
  baseURL: '', // api 的 base_url
  timeout: 60000 // 请求超时时间
});

// request拦截器
http.interceptors.request.use(
  (config) => {
    if (config.method === 'post' && (config.headers as any)['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data);
    }
    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url as string;
      url += '?';
      const keys = Object.keys(config.params);
      for (const key of keys) {
        if (config.params[key] !== undefined && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`;
        }
      }
      url = url.substring(0, url.length - 1);
      config.params = {};
      config.url = url;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error.response ? error.response : error);
  }
);

// response 拦截器
http.interceptors.response.use(
  (response: AxiosResponse<Recordable>) => {
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer || response.data instanceof Blob) {
      return response;
    }
    if ((response.status >= 200 && response.status < 300) || (response.data && response.data.Status !== undefined)) {
      return response;
    }
    throw new Error('接口返回数据格式有误。');
  },
  (error: AxiosError) => {
    return Promise.reject(error.response ? error.response : error);
  }
);

export { http };
